import { Request, Response, NextFunction } from "express";
import { usersTable } from "../../database/users-table";
import { decodeToken } from "../../helpers/token-decoder";

interface Params {
	token: string;
}
export default async (request: Request, response: Response, next: NextFunction) => {
	try {
		const params = request.body as unknown as Params;
		const user = decodeToken(params.token);
		if (!user) throw new Error("Token error");
		const token = usersTable.login(user.username);
		response.statusCode = 200;
		response.json({ token });
	} catch (error) {
		response.statusCode = 400;
		next(error);
	}
};
